﻿using System;
using System.Collections.Generic;
using System.Net.Mail;
using System.Text;
using System.Web;
using System.Web.Security;

namespace SelArom.Net.Sitefinity.HttpModules
{
	/// <summary>
	/// NOT IMPLEMENTED!!
	/// HttpModule for intercepting changes to pages and notifying approvers/publishers.
	/// </summary>
	public class PageNotifications : IHttpModule
	{
		#region IHttpModule Members

		public void Dispose()
		{
			
		}

		public void Init(HttpApplication context)
		{
			Telerik.Cms.CmsManager.Executing += CmsManager_Executing;
		}

		public void CmsManager_Executing(object sender, Telerik.ExecutingEventArgs e)
		{
			if (e.CommandName.ToLower() != "approve") return;

			// Get information about the CMS page being modified.     
			var content = e.CommandArguments as Telerik.Cms.Data.CmsPageContent;
			if (content == null) return;
			var message = new MailMessage(Membership.GetUser().Email, Membership.GetUser("admin").Email);

			message.Subject = "Page: " + content.Title + " - By: " + message.To[0];
			var body = "Title: " + content.Title + "\n" +
			              "Version: " + content.Version + "\n" +
			              "Date Created:" + content.DateCreated + "\n" +
			              "Date Modified:" + content.DateModified + "\n" +
			              "Description:" + content.CmsPage.Description + "\n" +
			              "\nView this page:\n" + FixupUrl(content.DefaultUrl.Url) + "\n" +
			              "\nEdit this page:\n" + FixupUrl("~/Sitefinity/admin/pages.aspx?select=" + content.ID) + "\n";
			message.Body = body;

			// Send the email.       
			var client = new SmtpClient();
			client.Send(message);
		}

		/// <summary>   
/// This method accept a short URL (example: ~/page.aspx) and converts it to a full URL. 
///    /// (example: http://www.fullwebsite.com:81/parent%20directory/page.aspx) 
///    /// </summary>  
		public static string FixupUrl(string Url)
		{
			var request = HttpContext.Current.Request;
			var Port = request.ServerVariables["SERVER_PORT"];
			if (Port == null || Port == "80" || Port == "443")
				Port = "";
			else
				Port = ":" + Port;
			string Protocol = request.ServerVariables["SERVER_PORT_SECURE"];
			if (Protocol == null || Protocol == "0")
				Protocol = "http://";
			else
				Protocol = "https://";
			string newUrl = Url;
			if (newUrl.StartsWith("~"))
				newUrl = (request.ApplicationPath + newUrl.Substring(1)).Replace("//", "/");
			newUrl = Protocol + request.ServerVariables["SERVER_NAME"] + Port + newUrl;
			return newUrl.Replace(" ", "%20");
		}


		#endregion
	}
}
